package com.xzzz.irda.auth.server.authentication;

import com.xzzz.irda.auth.core.AuthBaseProperties;
import com.xzzz.irda.auth.server.AuthServerConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.List;

/**
 * 系统处理配置
 * <p>
 * 用于将各类处理器注入到IOC中
 *
 * @author wangyf
 * 
 */
@Slf4j
@Configuration
public class AuthServerManagerConfiguration {

    @Bean
    public GrantTypeHandler requestDispatch(AuthBaseProperties authBaseProperties) {
        return new GrantTypeHandler(authBaseProperties);
    }

    @Primary
    @Bean(name = "authenticationManagerStrategy")
    public AuthenticationManager authenticationManagerStrategy(List<AuthenticationManager> authenticationManagerList) {
        return new AuthenticationManagerStrategy(authenticationManagerList);
    }

    @Bean(name = "authenticationManagerInner")
    public AuthenticationManager authenticationManagerInner(
            AuthServerConfiguration authServerConfiguration,
            AuthBaseProperties authBaseProperties) {
        return new AuthenticationInnerManager(authServerConfiguration, authBaseProperties);
    }

    @Bean(name = "authenticationManagerPassword")
    public AuthenticationManager authenticationManagerPassword(
            AuthServerConfiguration authServerConfiguration,
            AuthBaseProperties authBaseProperties) {
        return new AuthenticationPasswordManager(authServerConfiguration, authBaseProperties);
    }

    @Bean(name = "authenticationManagerPhone")
    public AuthenticationManager authenticationManagerPhone(
            AuthServerConfiguration authServerConfiguration,
            AuthBaseProperties authBaseProperties) {
        return new AuthenticationPhoneManager(authServerConfiguration, authBaseProperties);
    }

    @Bean(name = "authenticationManagerWxOpenId")
    public AuthenticationManager authenticationManagerWxOpenId(
            AuthServerConfiguration authServerConfiguration,
            AuthBaseProperties authBaseProperties) {
        return new AuthenticationWxOpenIdManager(authServerConfiguration, authBaseProperties);
    }

    @Bean
    public TokenService tokenService(List<AuthenticationManager> authenticationManagerList, GrantTypeHandler grantTypeHandler) {
        AuthenticationManagerStrategy authenticationManagerStrategy = null;
        for (AuthenticationManager authenticationManager : authenticationManagerList) {
            if (authenticationManager.getGrantType() == null) {
                authenticationManagerStrategy = (AuthenticationManagerStrategy) authenticationManager;
            }
        }

        if (authenticationManagerStrategy == null) {
            throw new NullPointerException("[AUTHORIZ] authenticationManagerStrategy is null");
        }

        return new TokenService(authenticationManagerStrategy, grantTypeHandler);
    }
}
